const dayjs = require('dayjs');

const { Controller } = require('varal');
const { sequelize, Withdrawal, UserPromoter } = require('../../models');
const { QueryTypes, Op } = require('sequelize');

const Weapp = require('../../libs/weapp');

class UserController extends Controller {
	async profile(app) {
		const { id } = app.auth;

		const serv = this.app.service("UserService");
		const data = await serv.info({ id }).then((data) => data.toJSON()) || {};
		if (!data?.id) return this.app.error('', { status: 401 });

		//获取qrcode
		const weapp = new Weapp();
		const { open_id } = data;
		data.qrcode = await weapp.qrcode(open_id, 'pages/order/work').then((url) => `https://mp.kachewo.com/uploadfile/qrcode/${url}`);

		if (!data.url_scheme || !data.url_scheme_expired || dayjs(data.url_scheme_expired) < dayjs()) {
			const { url_link } = await weapp.urlscheme('pages/order/work', `scene=${open_id}`);
			data.url_scheme = url_link;

			await serv.save({
				id,
				url_scheme: url_link,
				url_scheme_expired: dayjs().add(30, 'day').format('YYYY-MM-DD HH:mm:ss')
			});
		}

		const confServ = this.app.service('ConfigService');
		data.config = await confServ.info();

		//判断当前用户是否拥有首单优惠
		const { is_coupon, coupon_amount, coupon_name, coupon_intro, ad_image, ad_url } = await this.app.service("ConfigService").info();
		if (is_coupon === 0) {
			data.is_coupon = 0;
			data.coupon = {};
		} else {
			data.is_coupon = 1;
			data.coupon = {
				amount: coupon_amount,
				name: coupon_name,
				intro: coupon_intro
			}
		}

		data.ad_image = ad_image;
		data.ad_url = ad_url;

		//可提现金额=余额-审核中的提现总额
		const withdrawalin_amount = await Withdrawal.sum('amount', {
			where: {
				user_id: id,
				status: 0
			}
		});

		//单次可申请最大提现金额
		data.withdrawable_amount = Math.min(data.balance - parseFloat(withdrawalin_amount || 0), 10000);

		//判断当前用户是否使用过首单优惠
		const { id: order_id } = await this.app.service('OrderService').info({
			user_id: this.app.auth.id,
			pay_status: 1,
			coupon_amount: {
				[Op.gt]: 0
			}
		}).then((data) => data || ({}));

		if (order_id) {
			data.is_coupon = 0;
			data.coupon = {};
		}

		//await this.app.service('JournalService').dispatch('202404141421283051');

		//获取提款信息
		const { bank, bank_account, bank_account_no } = await Withdrawal.findOne({
			where: {
				user_id: this.app.auth.id
			}
		}) || {};
		if (bank) {
			data.bank = bank;
			data.bank_account = bank_account;
			data.bank_account_no = bank_account_no;
		}

		this.app.json({
			err_code: 0,
			data
		})
	}

	async login() {
		const weapp = this.app.make(Weapp);

		//使用手机号授权登录
		const { code, sns_code, scene } = this.app.fields;
		const { openid: open_id } = await weapp.snsSession(sns_code);

		const { errcode: err_code, errmsg: err_msg, phone_info = {} } = await weapp.userPhone(code);
		const { phoneNumber: phone } = phone_info;

		//判断用户是否存在，不存在则创建
		const serv = this.app.service('UserService');
		return serv.loginByPhone(phone, open_id, scene).then((data) => {
			return this.app.json({
				err_code: 0,
				data
			})
		}).catch((err) => {
			return this.app.json({
				err_code: 1,
				err_msg: err.toString()
			})
		})
	}

	//保存用户信息
	async save(app) {
		const { id } = app.auth;
		const serv = this.app.service("UserService");
		await serv.save({
			...app.fields,
			id
		});

		this.app.json({
			err_code: 0
		})
	}

	async tree(app) {
		const { id } = app.auth;
		const { page = 1 } = app.fields;

		const serv = this.app.service("UserService");
		const data = await serv.get({ tree_id: id, team_id: id }, 1, 1000).then(({ data }) => {
			return data.map(({ dataValues: d }) => {
				const remark = d.tree_remark ?? d.team_remark ?? '';
				d.tree_remark = d.team_remark = remark;

				d.create_time = dayjs(d.create_time).format('YYYY-MM-DD HH:mm:ss');

				return d;
			})
		});

		this.app.json({
			err_code: 0,
			data
		})
	}

	//用户备注
	async remark(app) {
		const { role_id } = app.auth;

		const { user_id, remark } = app.fields;
		const serv = this.app.service('UserService');

		//数字推广官
		if (role_id === 4) {
			serv.save({
				id: user_id,
				team_remark: remark
			})
		} else {
			serv.save({
				id: user_id,
				tree_remark: remark
			})
		}

		app.json({
			err_code: 0
		})
	}

	//数字推广官申请
	async promoter(app) {
		const params = app.fields;
		Object.keys(params).forEach((key) => {
			if (require('util').isArray(params[key])) params[key] = params[key].join(',');
		});

		params.user_id = app.auth.id;
		await UserPromoter.create(params);

		app.json({
			err_code: 0
		})
	}
}

exports = module.exports = UserController;
